<template>
  <div class="app-container">
    <!-- 表格 -->
    <div class="form-action">
      <el-button type="success" size="mini" @click="handleAdd"> 新增 </el-button>
    </div>
    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label="ID" width="95">
        <template slot-scope="scope">
          {{ scope.$index + 1 + (pagination.pageNumber - 1) * pagination.pageSize }}
        </template>
      </el-table-column>
      <el-table-column label="图片地址">
        <template slot-scope="scope">
          <img :src="scope.row.carousel" alt="图片" width="auto" height="60">
        </template>
      </el-table-column>
      <el-table-column label="是否现在启用">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.is_use"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="启用"
            inactive-text="不启用"
            @change="useChane(scope.row.is_use, scope.row._id)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="更新日期" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.date }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleEdit(scope.row._id, scope.row.is_use)">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDel(scope.row._id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="block">
      <el-pagination
        background
        :current-page.sync="pagination.pageNumber"
        :page-size="pagination.pageSize"
        layout="total, prev, pager, next"
        :total="pagination.total"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 弹框 -->
    <el-dialog
      v-loading="loading"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :before-close="beforeClose"
    >
      <el-upload
        ref="upload"
        class="upload"
        action="action"
        :auto-upload="false"
        :http-request="uploadBanner"
        :before-upload="beforeUpload"
        :on-change="handleChange"
        :limit="1"
      >
        <el-button size="medium" type="primary" class="el-icon-upload">选择图片</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
      <el-row :gutter="20" style="margin-top: 15px">
        <el-col :span="6" style="line-height: 30px"> 是否现在启用： </el-col>
        <el-col :span="6">
          <el-select v-model="is_use" size="mini" placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel"> 取消 </el-button>
        <el-button type="primary" @click="submitData"> 提交 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getBnnerList, addBanner, delBanner, editBanner, isuseBanner } from '@/api/banner'
export default {
  name: 'Banner',
  data() {
    return {
      pagination: {
        total: 0,
        pageSize: 10,
        pageNumber: 1
      },
      options: [
        {
          value: true,
          label: '启用'
        },
        {
          value: false,
          label: '不启用'
        }
      ],
      // 是否有文件提交数据
      ishaveData: false,
      list: null,
      listLoading: false,
      loading: false,
      dialogFormVisible: false,
      dialogStatus: '',
      editId: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      is_use: false,
      formData: null
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 选择页码
    handleCurrentChange(val) {
      this.pagination.pageNumber = val
      this.fetchData()
    },
    // 切换启用轮播图
    async useChane(value, id) {
      console.log('value: ', value)
      console.log('id: ', id)
      try {
        await isuseBanner({
          id,
          is_use: value
        })
        this.fetchData()
      } catch (error) {
        console.log('error: ', error)
      }
    },
    // 弹框取消按钮
    cancel() {
      this.dialogFormVisible = false
      this.$refs.upload.clearFiles()
    },
    // 弹框关闭之前清空文件
    beforeClose(done) {
      this.$refs.upload.clearFiles()
      done()
    },
    // 编辑图片按钮
    handleEdit(id, is_use) {
      this.dialogFormVisible = true
      this.dialogStatus = 'update'
      this.ishaveData = false
      this.editId = id
      this.is_use = is_use
    },
    // 删除图片按钮
    handleDel(_id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await delBanner(_id)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.fetchData()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 新增图片按钮
    handleAdd() {
      this.dialogFormVisible = true
      this.dialogStatus = 'create'
      this.is_use = false
      this.ishaveData = false
    },

    // 拉表格数据
    async fetchData() {
      var { pageSize, pageNumber } = this.pagination
      this.listLoading = true
      try {
        const response = await getBnnerList({ pageSize, pageNumber })
        console.log('response: ', response)
        this.list = response.data
        this.listLoading = false
        this.pagination = response.pagination
      } catch (error) {
        console.log('error: ', error)
        this.listLoading = false
      }
    },
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    handleChange(file) {
      console.log('file: ', file)
      if (file.size) {
        this.ishaveData = true
      } else {
        this.ishaveData = true
      }
    },
    // 上传文件之前钩子
    beforeUpload(file) {
      const type = file.name.substring(file.name.lastIndexOf('.') + 1)
      const typeInfo = ['jpg', 'png', 'jpeg']
      if (!typeInfo.includes(type)) {
        this.$message({
          type: 'error',
          message: '只支持jpg,png,jpeg文件格式！'
        })
        this.ishaveData = false
        return false
      }
      if (file.size / 1024 > 500) {
        this.$message({ type: 'error', message: '图片不能大于500kb！' })
        this.ishaveData = false
        return false
      }
      const formData = new FormData()
      formData.append('files', file)
      formData.append('is_use', this.is_use)
      this.formData = formData
    },
    // 新增或者编辑提交
    submitData() {
      if (this.ishaveData === false) {
        this.$message({
          type: 'error',
          message: '请选择图片'
        })
        return
      }
      this.$refs.upload.submit()
    },

    // 新增或编辑图片请求
    async uploadBanner() {
      this.loading = true
      const formData = this.formData
      // 编辑逻辑
      if (this.dialogStatus === 'update') {
        try {
          await editBanner(this.editId, formData)
          this.$message({
            type: 'success',
            message: '编辑轮播图成功'
          })
          this.loading = false
          this.dialogFormVisible = false
          this.ishaveData = false
          this.$refs.upload.clearFiles()
          // 重新拉数据
          this.fetchData()
        } catch (error) {
          console.log('error: ', error)
          this.loading = false
        }
      } else {
        // 新增逻辑
        try {
          await addBanner(formData)
          this.$message({
            type: 'success',
            message: '添加轮播图成功'
          })
          this.loading = false
          this.dialogFormVisible = false
          this.ishaveData = false
          this.$refs.upload.clearFiles()
          // 重新拉数据
          this.fetchData()
        } catch (error) {
          console.log('error: ', error)
          this.loading = false
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.form-action {
  margin-bottom: 20px;
  overflow: hidden;
  button {
    float: right;
  }
}
.block {
  margin-top: 20px;
  text-align: center;
}
</style>
